package main

import (
	"compress/gzip"
	"encoding/json"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
)

func initRouter(r *gin.Engine) {
	r.GET("/index.html", func(c *gin.Context) {
		content, err := StaticFS.ReadFile("static/index.html")
		if err != nil {
			c.String(http.StatusInternalServerError, "无法读取文件")
			return
		}
		c.Data(http.StatusOK, "text/html; charset=utf-8", content)
	})

	r.GET("/", func(c *gin.Context) {
		c.Redirect(http.StatusMovedPermanently, "/index.html")
	})

	r.GET("/data", func(c *gin.Context) {
		// Start Generation Here
		w := gzip.NewWriter(c.Writer)
		defer w.Close()
		c.Writer.Header().Set("Content-Encoding", "gzip")
		c.Writer.Header().Set("Content-Type", "application/json")
		id := c.Query("id")
		var queryLongId int64
		var err error
		if id == "" {
			queryLongId = 0
		} else {
			queryLongId, err = strconv.ParseInt(id, 10, 64)
			if err != nil {
				c.String(http.StatusInternalServerError, "id 错误")
				return
			}
		}
		var sqls []*SqlStruct
		for i := len(SQLS) - 1; i >= 0; i-- {
			var longId, err = strconv.ParseInt(SQLS[i].Id, 10, 64)
			if err != nil {
				continue
			}
			if queryLongId >= longId {
				break
			}
			sqls = append(sqls, SQLS[i])
		}
		if err := json.NewEncoder(w).Encode(gin.H{
			"sqls": sqls,
		}); err != nil {
			c.String(http.StatusInternalServerError, "无法压缩数据")
			return

		}
	})

	r.GET("/result", func(c *gin.Context) {
		id := c.Query("id")
		for _, sql := range SQLS {
			if sql.Id == id {
				c.JSON(http.StatusOK, gin.H{
					"result": sql.Result,
				})
				return
			}
		}
	})
}

func startManager(port string) {
	gin.SetMode(gin.ReleaseMode) // 设置为 Release 模式
	r := gin.New()               // 创建新的引擎实例
	r.Use(gin.Recovery())        // 使用恢复中间件
	initRouter(r)
	r.Run(":" + port) // 在8080端口启动服务器
}
